/**
 * @description Sogou Cloud Pinyin Extension for Chrome (Chromium) 
 * @author ZHANG Bei(A.K.A Shinjikun(toaru...)), 
 * iTechs Laboratory, ISCAS, China
 * 
 * <a href="http://www.opensource.org/licenses/gpl-2.0.php">GPLv2</a> Licensed
 */
 
var customEvent = document.createEvent('Event');
customEvent.initEvent('sogouClose', true, true);

function postImeClose() {
	localStorage['enabled'] = (window.ime_close == 0) ? 'open' : 'close';
	if (window.ime_close == 1)
		window.dispatchEvent(customEvent);

}

function sogouClosePinyin() {
	localStorage['enabled'] = 'close';
	if (typeof(window.ime_close) == 'undefined')
		return;
	if (window.ime_close == 0)
		window.imeClose();
}

function sogouOpenPinyin() {
	localStorage['enabled'] = 'open';
	if (typeof(window.ime_close) == 'undefined') {
		{
			var element = document.createElement('script');
			element.setAttribute('src',
					'http://web.pinyin.sogou.com/web_ime/init2.php');
			element.id = "sogou-ime-pad-import-src";
			element.addEventListener('load', function() {
				document.getElementById('sogou-pinyin-loading-tip').style.opacity = 0;

				function fireCustomEvent(data) {
					hiddenDiv = document.getElementById('myCustomEventDiv');
					hiddenDiv.innerText = data
					hiddenDiv.dispatchEvent(customEvent);
				}

				var saveImeClose = window.imeClose;
				window.imeClose = function() {
					saveImeClose();
					postImeClose();
				}
			});
			document.body.appendChild(element);

		}
		{
			var element = document.createElement('div');
			element
					.setAttribute(
							'style',
							'position: absolute; left: 0px; top: 0px;'
									+ 'margin: 0px; padding: 2px; background-color: #ACF; border: 1px solid #99F; -webkit-transition: all 0.5s ease-out; opacity:0');
			element.id = "sogou-pinyin-loading-tip";
			element.innerHTML = '正在载入搜狗云输入法...';
			document.body.appendChild(element);
			window.setTimeout(function() {
						element.style.opacity = 0.8;
					}, 10);
		}
	} else if (window.ime_close == 1)
		window.imeClose();
}

function checkState() {
	if (localStorage['enabled'] == 'open')
		sogouOpenPinyin();
	else
		sogouClosePinyin();
}

checkState();
